#include <stdlib.h>
#include <stdio.h>

#include "vus_test.h"
#include "vus_test_frame.h"
#include "vus_test_video_ffmpeg.h"

static const char * cmdName = "vus_test_open_video";

void ShowHelp() {
	fprintf(stderr,"FFMPEG TESTS: \n");
	fprintf(stderr,"%s <input_video> \n", cmdName);
}

//a simple script to write a ppm file
//kudos to drainger's ffmpeg tutorials.
void SaveFrame(vus_frame * frame, int width, int height, int iFrame) {
	FILE *pFile;
	char szFilename[32];
	int  y;

	// Open file
	sprintf(szFilename, "frame%d.ppm", iFrame);
	pFile=fopen(szFilename, "wb");
	if(pFile==NULL)
		return;

	// Write header
	fprintf(pFile, "P6\n%d %d\n255\n", width, height);

	// Write pixel data
	for(y=0; y<height; y++)
		fwrite(frame->data[0]+y*frame->linesize[0], 1, width*3, pFile);

	// Close file
	fclose(pFile);
}



int main(int argc, char** argv) {
	vus_test_resource_video_ffmpeg * test;
	vus_frame * frame;
	int i = 0;

	if (argc < 2) {
		ShowHelp();
		return -1;
	}

	test = vus_test_resource_video_ffmpeg_alloc();
	if (test) {
		vus_test_resource_video_ffmpeg_open(test, argv[1]);
		while (i < 6) {
			frame = vus_test_resource_video_ffmpeg_get_next_frame(test);
			if (frame == NULL)
				break;
			if (++i < 6) {
				SaveFrame( frame, frame->width, frame->height, i);
			}
			vus_frame_free(&frame);
		}
	}


	vus_test_resource_video_ffmpeg_free(&test);

	return -1;
}
